import React, { useState } from 'react'
import CarouselCard from './CarouselCard'

function getAnimateDirection(current, next, count) {
  if (current === 0) {
    if (next === count - 1) {
      return 'right'
    } else {
      return 'left'
    }
  } else if (current === count - 1) {
    if (next === 0) {
      return 'left'
    } else {
      return 'right'
    }
  } else {
    if (current > next) {
      return 'right'
    } else {
      return 'left'
    }
  }
}

function getAnimateClassName(current, next, count, type) {
  if (next === -1) return ''
  return getAnimateDirection(current, next, count) + type
}

const Carsousel2 = ({ children }) => {
  const count = React.Children.count(children)
  if (count <= 1 || !children.every((el) => el.type === CarouselCard)) {
    throw new Error(
      'Carousel2 的children必须为CarouselCard元素的数组，' + '而且长度不小于2'
    )
  }
  const [current, setCurrent] = useState(0)
  const [next, setNext] = useState(-1)

  let currentCard = children[current]
  currentCard = React.cloneElement(currentCard, {
    ...currentCard.props,
    className:
      currentCard.props.className +
      ' item animate ' +
      getAnimateClassName(current, next, count, 'Out'),
    onAnimationEnd: () => {
      setCurrent(next)
      setNext(-1)
    },
  })
  let nextCard = children[next]
  nextCard =
    nextCard &&
    React.cloneElement(nextCard, {
      ...nextCard.props,
      className:
        nextCard.props.className +
        ' item animate ' +
        getAnimateClassName(current, next, count, 'In'),
    })

  return (
    <div>
      <div className="carousel2">
        {currentCard}
        {nextCard}
      </div>
      <button
        onClick={() => {
          if (next === -1) {
            const next = current - 1
            setNext(next < 0 ? count - 1 : next)
          }
        }}
      >
        ⬅️
      </button>
      <button
        onClick={() => {
          if (next === -1) {
            const next = current + 1
            setNext(next >= count ? 0 : next)
          }
        }}
      >
        ➡️
      </button>
    </div>
  )
}

export default Carsousel2
